<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Exception;
use think\Hook;
use app\common\library\Token;


/**
 * 登录接口
 */
class Login extends Api
{

    protected static $instance = null;
    protected $_logined = false;
    protected $_user = null;
    protected $_token = '';
    //Token默认有效时长
    protected $keeptime = 2592000;
    protected $rules = [];

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * @ApiTitle    (注册)
     * @ApiSummary  (注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/register)
     * @ApiParams   (name="mobile", type="varchar", required=true, description="电话")
     * @ApiParams   (name="captcha", type="varchar", required=true, description="验证码")
     * @ApiParams   (name="pass", type="varchar", required=true, description="密码")
     * @ApiParams   (name="ip", type="varchar", required=true, description="ip地址")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "注册成功",
    "time": "1635239212",
    "data": null

     * })
     */
    public function register()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $password = $this->request->post('pass');
        $ip = $this->request->post('ip');
        if (empty($mobile)) {
            $this->error(__('请完善信息'));
        }
        $userinfo = Db::name('personal')->where('mobile',$mobile)->find();
        if ($userinfo) {
            $this->error(__('已被注册'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号'));
        }
        if (!Sms::check($mobile, $captcha, 'register')) {
            $this->error(__('请填写正确的验证码'));
        }
        if (!Validate::is($password, '\S{8,20}')) {
            $this->error(__('密码不合格'));
        }
        $salt = Random::alnum();
        $pass = md5(md5($password) . $salt);
        $a1 = Random::build();
        $a2 = Random::numeric();
        $a3 = Random::alnum();
        $username = 'u_' . $a1.$a3 . '_c' . $a2 ;
        $ret = [
            'account'   =>  $mobile,
            'avatar'    =>  '/assets/img/avatar.png',
            'nickname'  =>  $username,
            'ip'    =>  $ip,
            'pass'  =>  $pass,
            'salt'  =>  $salt,
            'mobile'    =>  $mobile,
            'createtime'    =>  time()
        ];
        $data = Db::name('personal')->insert($ret);
        if ($data) {
            $this->success('注册成功');
        } else {
            $this->error('注册失败');
        }
    }
    
    /**
     * 微信登录绑定手机号
     * login_type : 1:微信，2、支付宝,3、QQ登录，4、手机微信登录
     */
    public function vxregist()
    {
        $mobile = $this->request->post('mobile');
        $openid = $this->request->post('openid');
        $captcha = $this->request->post('captcha');
        $password = $this->request->post('pass');
        $login_type = $this->request->post("login_type",1);
        // $event = $this->request->post('event');
        $ip = $this->request->post('ip');
        if (empty($mobile)) {
            $this->error(__('请完善信息'));
        }
        $token = Random::uuid();
        
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号'));
        }
        if (!Sms::check($mobile, $captcha, 'vxregist')) {
            $this->error(__('请填写正确的验证码'));
        }
        $userinfo = Db::name('personal')->where('mobile',$mobile)->find();
        if ($userinfo) {
            // if($login_type == 1){
            //     $ret = [
            //         'openid'=>$openid,
            //         'token'=>$token
            //     ];
            // }else{
            //     $ret = [
            //         'ali_appid'=>$openid,
            //         'token'=>$token
            //     ];
            // }
            $ret['token'] = $token;
            switch ($login_type){
                case 2:
                    $ret['ali_appid'] = $openid;
                    break;
                case 3:
                    $ret['qqopenid'] = $openid;
                    break;
                case 4:
                    $ret['app_vxopenid'] = $openid;
                    break;
                default :  
                    $ret['openid'] = $openid;
                    break;
            }
            
            $data = DB::name("personal")->where("id",$userinfo['id'])->update($ret);    
        }else{
            // $password = '0000001';
            $salt = Random::alnum();
            $pass = md5(md5($password) . $salt);
            $a1 = Random::build();
            $a2 = Random::numeric();
            $a3 = Random::alnum();
            $username = 'u_' . $a1.$a3 . '_c' . $a2 ;
            $ret = [
                'account'   =>  $mobile,
                'avatar'    =>  '/assets/img/avatar.png',
                'nickname'  =>  $username,
                'ip'    =>  $ip,
                'pass'  =>  $pass,
                'salt'  =>  $salt,
                'mobile'    =>  $mobile,
                'createtime'    =>  time(),
                'openid'=>$openid,
                'token'=>$token
            ];
            $data = Db::name('personal')->insert($ret);
        }
        
        if ($data) {
            $this->success('注册成功',$token);
        } else {
            $this->error('注册失败');
        }
    }




    /**
     * @ApiTitle    (登录)
     * @ApiSummary  (登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/login)
     * @ApiParams   (name="type", type="varchar", required=true, description="1账号登录 2短信登录")
     * @ApiParams   (name="account", type="varchar", required=false, description="1账号")
     * @ApiParams   (name="pass", type="varchar", required=false, description="1密码")
     * @ApiParams   (name="mobile", type="varchar", required=false, description="2电话")
     * @ApiParams   (name="captcha", type="varchar", required=false, description="2验证码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "登录成功",
    "time": "1635241101",
    "data": null

     * })
     */
    public function login()
    {
        $type = $this->request->post('type');
        $account = $this->request->post('account');
        $pass = $this->request->post('pass');
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $ip = request()->ip();
        $token = Random::uuid();
        if ($type == 1) {
            $acc = Db::name('personal')->where('account',$account)->find();
            if (empty($acc)) {
                $this->error('没有此账号');
            }
            if ($acc['switch'] == 0) {
                $this->error('账号已冻结');
            }
            if ($acc['pass'] != $this->getEncryptPassword($pass,$acc['salt'])) {
                $this->error('账号密码错误');
            }
            $log = Db::name('personal')->where('id',$acc['id'])->update(['token'=>$token,'logintime'=>time(),'ip'=>$ip]);
            if ($log) {
                $this->success('登录成功',$token);
            } else {
                $this->error('登录失败');
            }
        } else {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('请填写正确的手机号'));
            }
            if (!Sms::check($mobile, $captcha, 'login')) {
                $this->error(__('请填写正确的验证码'));
            }
            $acc = Db::name('personal')->where('account',$mobile)->find();
            if (empty($acc)) {
                $this->error('没有此账号');
            }
            if ($acc['switch'] == 0) {
                $this->error('账号已冻结');
            }
            $log = Db::name('personal')->where('id',$acc['id'])->update(['token'=>$token,'logintime'=>time(),'ip'=>$ip]);
            if ($log) {
                $this->success('登录成功',$token);
            } else {
                $this->error('登录失败');
            }
        }
    }


    /**
     * @ApiTitle    (找回密码1)
     * @ApiSummary  (找回密码1)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/retrieve)
     * @ApiParams   (name="mobile", type="varchar", required=false, description="2电话")
     * @ApiParams   (name="captcha", type="varchar", required=false, description="2验证码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "注册成功",
    "time": "1627553755",
    "data": {
    'id':用户id

     * })
     */
    public function retrieve()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (empty($mobile)) {
            $this->error(__('请完善信息'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('请填写正确的手机号'));
        }
        if (!Sms::check($mobile, $captcha, 'retrieve')) {
            $this->error(__('请填写正确的验证码'));
        }
        $acc = Db::name('personal')->where('account',$mobile)->find();
        if (empty($acc)) {
            $this->error('没有此账号');
        } else {
            $this->success('ok',$acc['id']);
        }
    }

    /**
     * @ApiTitle    (找回密码2)
     * @ApiSummary  (找回密码2)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/forgot)
     * @ApiParams   (name="id", type="varchar", required=false, description="用户id")
     * @ApiParams   (name="pass", type="varchar", required=false, description="密码")
     * @ApiParams   (name="password", type="varchar", required=false, description="重复密码")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "注册成功",
    "time": "1627553755",
    "data": {
    'id':1

     * })
     */
    public function forgot()
    {
        $id = $this->request->post('id');
        $pass = $this->request->post('pass');
        $password = $this->request->post('password');
        if (!Validate::is($pass, '\S{8,20}')) {
            $this->error(__('密码不合格'));
        }
        if ($pass != $password) {
            $this->error(__('新密码不一致'));
        }
        $salt = Random::alnum();
        $pass1 = $this->getEncryptPassword($pass,$salt);
        $data = Db::name('personal')->where('id',$id)->update(['pass'=>$pass1,'salt'=>$salt]);
        if ($data) {
            $this->success('找回密码成功');
        } else {
            $this->error('找回密码失败');
        }
    }



    /**
     * @ApiTitle    (退出登录)
     * @ApiSummary  (退出登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/out)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "退出成功",
    "time": "1627553755",

     * })
     */
    public function out()
    {
        $token = $this->request->header('token');
        Db::name('personal')->where('token',$token)->update(['token'=>'']);
        $this->success('退出成功');
    }


    /**
     * @ApiTitle    (获取名字)
     * @ApiSummary  (获取名字)
     * @ApiMethod   (POST)
     * @ApiRoute    (api/Login/getName)
     * @ApiHeaders	(name=token, type=string, required=true, description="请求的Token")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    "code": 1,
    "msg": "退出成功",
    "time": "1627553755",

     * })
     */
    public function getName()
    {
        $token = $this->request->header('token');
        $res['name'] = Db::name('personal')->where('token',$token)->value('nickname');
        $res['receset'] = Db::name('personal')->where('token',$token)->value('receset');
        $this->success('ok',$res);
    }



    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
        return md5(md5($password) . $salt);
    }


}
